﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Security.Permissions;
using System.Reflection;
using mshtml;

namespace StockDisplay
{
    /// <summary>
    /// Interaction logic for NewsWindow.xaml
    /// </summary>
    public partial class NewsWindow : Window
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public NewsWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(NewsWindow_Loaded);
            Browser1.Navigated += new System.Windows.Navigation.NavigatedEventHandler(Browser1_Navigated);
        }

        /// <summary>
        /// Focuses the HTML document so that dialog window has the default focus
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Browser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            mshtml.IHTMLDocument2 doc = Browser1.Document as mshtml.IHTMLDocument2;
            if (doc == null) return;
            if (doc.parentWindow == null) return;
            doc.parentWindow.focus();
        }

        /// <summary>
        /// Supresses javascript permissions errors
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewsWindow_Loaded(object sender, RoutedEventArgs e)
        {
            SuppressScriptErrors(Browser1, true);
        }

        /// <summary>
        /// Supress Script Errors
        /// </summary>
        /// <param name="wb">The web browser control</param>
        /// <param name="Hide">Flag to set silent mode</param>
        private void SuppressScriptErrors(System.Windows.Controls.WebBrowser wb, bool Hide)
        {
            FieldInfo fi = typeof(System.Windows.Controls.WebBrowser).GetField(
                "_axIWebBrowser2",
                BindingFlags.Instance | BindingFlags.NonPublic);

            if (fi != null)
            {
                object browser = fi.GetValue(wb);

                if (browser != null)
                {
                    browser.GetType().InvokeMember("Silent", BindingFlags.SetProperty,
                        null, browser, new object[] { Hide });
                }
            }
        }
    }
}
